import axios from "axios";
import { createUniAppAxiosAdapter } from "@uni-helper/axios-adapter";
import type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { getUserInfo } from "@/utils/storage";

/*创建axios的实例*/
const request: AxiosInstance = axios.create({
    adapter: createUniAppAxiosAdapter(),
    baseURL: "https://pcapi-xiaotuxian-front-devtest.itheima.net",
    timeout: 10000,
});

/*添加请求拦截器*/
request.interceptors.request.use(async (config: InternalAxiosRequestConfig) => {
    await uni.showLoading({ title: "加载中···" });
    // 在发送请求之前做些什么
    const userInfo = getUserInfo();
    if (userInfo.token) {
        config.headers.Authorization = userInfo.token;
    }
    return config;
}, (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
});

/*添加响应拦截器*/
request.interceptors.response.use((response: AxiosResponse) => {
    // 2xx 范围内的状态码都会触发该函数。对响应数据做点什么
    uni.hideLoading();
    return response.data;
}, (error) => {
    uni.hideLoading();
    // 超出 2xx 范围的状态码都会触发该函数。对响应错误做点什么
    return Promise.reject(new Error(error.response.data.msg));
});


export default request;
